package com.fjzx.androidframe.ui.flow;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.fjzx.androidframe.ui.R;

/**
 * @author xiongyongcong
 */
public class BaseTagFlowLayout extends ConstraintLayout implements View.OnClickListener {
    protected TextView prefixText;
    protected ImageView btCollapse;
    protected TagFlowLayout flowLayout;

    public BaseTagFlowLayout(Context context) {
        this(context, null);
    }

    public BaseTagFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseTagFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BaseTagFlowLayout);
        String text = ta.getString(R.styleable.BaseTagFlowLayout_text);
        int resourceId = ta.getResourceId(R.styleable.BaseTagFlowLayout_text_res_id, -1);
        if (!TextUtils.isEmpty(text)) {
            prefixText.setText(text);
        }
        if (resourceId != -1) {
            prefixText.setText(resourceId);
        }
        ta.recycle();
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.common_tag_layout, this, true);
        prefixText = findViewById(R.id.prefix_text);
        btCollapse = findViewById(R.id.bt_collapse);
        flowLayout = findViewById(R.id.flow_layout);
        prefixText.setOnClickListener(this);
        btCollapse.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int visibility = flowLayout.getVisibility();
        int rotateDegree = visibility == GONE ? 90 : -90;
        btCollapse.animate().rotationBy(rotateDegree).setDuration(100).start();
        flowLayout.setVisibility(visibility == GONE ? VISIBLE : GONE);
    }

    public void setText(int textResId) {
        prefixText.setText(textResId);
    }

    public void setText(String text) {
        prefixText.setText(text);
    }

    public void setAdapter(TagAdapter adapter) {
        flowLayout.setAdapter(adapter);
    }

    public TagFlowLayout getFlowLayout() {
        return flowLayout;
    }
}
